﻿/// <summary>
/// Baidu face detect demo.
/// This demo use baidu url to detect the face
/// We use the first one of the detected users and draw landmark points on the image to show the situation of his face
/// </summary>


//press "C"  to show some datas ,  like  gender
using UnityEngine;
using System.Collections;
using System.Web;
using System.Collections.Generic;



public class BaiduFaceDetectDemo : MonoBehaviour {

		
	Texture2D tx;

	public WebCamCap mWebCamCap;

	string resultTxt=string.Empty;

	FaceStat[] facStats;

	public BaiduAIFaceMgr mBaiduFaceMgr;

	public GameObject DispObj;

	// Use this for initialization
	void Start () {
		tx	=new Texture2D(mWebCamCap.CamW, mWebCamCap.CamH, TextureFormat.RGB24, false);
	}

	// Update is called once per frame
	void Update () {
		Color32[] webColor=mWebCamCap.WebCameraTex.GetPixels32();


		//tx.SetPixels(mWebCamCap.WebCameraTex.GetPixels());
//	
//		if (Input.GetKeyDown(KeyCode.C))
//		{
			if(mBaiduFaceMgr.enableMarkDetedted)
			{
				tx.SetPixels32(webColor);
				tx.Apply();
				byte[] pngData = tx.EncodeToJPG ();
		    	StartCoroutine (mBaiduFaceMgr.PostImageToBaiduAI_detect (pngData));

			}
//			else
//			{
//				Debug.LogError("The last face detection is not finished yet.");
//			}
//		}

		if (Input.GetKeyDown(KeyCode.C))
		{
			mBaiduFaceMgr.LogGender();

		}

		_Landmark[] landmark4of1stdetectedUser=mBaiduFaceMgr.GetLandmark4FirstDetectedUser();
		_Landmark[] landmark72of1stdetectedUser=mBaiduFaceMgr.GetLandmark72FirstDetectedUser();

		if(landmark4of1stdetectedUser!=null)
		{	//The y coord a up side down.
			foreach(  _Landmark landmk in landmark4of1stdetectedUser  )
			{
				int ycoord=mWebCamCap.CamH-landmk.y;
				if(ycoord<0)ycoord=0;

				DrawingSpotsOnTexture.WhiteWriteSquare(mWebCamCap.CamW,mWebCamCap.CamH,landmk.x,ycoord,7,webColor,255,0,0);
			}
		}

		if(landmark72of1stdetectedUser!=null)
		{	//The y coord a up side down.
			foreach(  _Landmark landmk in landmark72of1stdetectedUser  )
			{
				int ycoord=mWebCamCap.CamH-landmk.y;
				if(ycoord<0)ycoord=0;

				DrawingSpotsOnTexture.WhiteWriteSquare(mWebCamCap.CamW,mWebCamCap.CamH,landmk.x,ycoord,3,webColor,255,0,255);
			}
		}



		tx.SetPixels32(webColor);
		tx.Apply();

		DispObj.GetComponent<Renderer>().material.mainTexture = tx;
	}


	void OnGUI()
	{
		GUILayout.Label("This demo shows the use of baidu face detecton\n");
		GUILayout.Label("We send out web cam image to the baidu url\n  and retrieve the json result");
		GUILayout.Label("In script BaiduFaceDetectDemo, we draw points on img to show the result ");



	}

}
